#include "StompedReality/Core/Game.h"
#include "StompedReality/Core/Graphics/RenderSystem.h"
#include "StomperLib/Gwen/GwenRenderer.h"
#include <Gwen/Font.h>
#include <Windows.h>
namespace StomperLib
{
namespace GwenBinding
{
struct GLFont
{
  HFONT hFont;
  GLuint listID;
};
void GwenRenderer::LoadFont( Gwen::Font* pFont )
{
  GLFont* glFont = new GLFont( );
  glFont->hFont = CreateFont( -pFont->size,         // Height Of Font
                              0, // Width Of Font
                              0, // Angle Of Escapement
                              0, // Orientation Angle
                              FW_BLACK, // Font Weight
                              false, // Italic
                              false, // Underline
                              false, // Strikeout
                              ANSI_CHARSET, // Character Set Identifier
                              OUT_TT_PRECIS, // Output Precision
                              CLIP_DEFAULT_PRECIS, // Clipping Precision
                              ANTIALIASED_QUALITY, // Output Quality
                              FF_DONTCARE|DEFAULT_PITCH, // Family And Pitch
                              pFont->facename.c_str( ) );
  glFont->listID = glGenLists( 255 );
  HDC hdc = (HDC) this->m_Game->RenderSystem( )->GetDisplayPointer( );
  HFONT oldfont = ( HFONT ) SelectObject( hdc, glFont->hFont );
  wglUseFontBitmaps ( hdc, 0, 255, glFont->listID );
  SelectObject( hdc, oldfont );
  pFont->data = glFont;
}

void GwenRenderer::FreeFont( Gwen::Font* pFont )
{
  if ( pFont->data == NULL )
    return;
  GLFont* glFont = (GLFont*) pFont->data;
  glDeleteLists( glFont->listID, 255 );
  DeleteObject( glFont->hFont );
}

void GwenRenderer::RenderText( Gwen::Font* pFont, Gwen::Point pos, const Gwen::UnicodeString& text )
{
  if ( pFont->data == NULL )
    return;
  GLboolean texturesOn;
  glGetBooleanv( GL_TEXTURE_2D, &texturesOn );
  if ( texturesOn )
  {
    glDisable( GL_TEXTURE_2D );
  }
  GLFont* glFont = (GLFont*) pFont->data;
  glListBase( glFont->listID );
  Gwen::Point p = MeasureText( pFont, text );
  Translate( pos.x, pos.y );
  glRasterPos2f( pos.x, pos.y + pFont->size * Scale( ) );
  char* out = new char[ text.length( )];
  wcstombs( out, text.data( ), text.length( ));
  glCallLists( text.length( ), GL_UNSIGNED_BYTE, out );
  delete[] out;
  if ( texturesOn )
    glEnable( GL_TEXTURE_2D );
}

Gwen::Point GwenRenderer::MeasureText( Gwen::Font* pFont, const Gwen::UnicodeString& text )
{
  if ( pFont->data == NULL )
    this->LoadFont( pFont );
  HDC hdc = (HDC) this->m_Game->RenderSystem( )->GetDisplayPointer( );
  GLFont* glFont = (GLFont*) pFont->data;
  HFONT oldfont = (HFONT)SelectObject( hdc, glFont->hFont );
  SIZE rect;
  GetTextExtentPoint32( hdc, text.c_str( ), text.length( ), &rect );
  SelectObject( hdc, oldfont );
  return Gwen::Point( rect.cx, rect.cy );
}

}
}